const express = require('express');
const router = express.Router();
const Reminder = require('../models/reminder.model');
const Medicine = require('../models/medicine.model');
const asyncHandler = require('express-async-handler');

// 获取用药提醒列表
router.get('/', asyncHandler(async (req, res) => {
  const { isActive, page = 1, limit = 10 } = req.query;
  const query = { userId: req.user.id };

  if (typeof isActive !== 'undefined') {
    query.isActive = isActive === 'true';
  }

  const skip = (page - 1) * limit;

  const [reminders, total] = await Promise.all([
    Reminder.find(query)
      .sort({ nextRemindTime: 1 })
      .skip(skip)
      .limit(Number(limit))
      .populate('medicineId', 'name imageUrl'),
    Reminder.countDocuments(query)
  ]);

  res.json({
    success: true,
    data: {
      reminders,
      total,
      page: Number(page),
      totalPages: Math.ceil(total / limit)
    }
  });
}));

// 获取今日提醒
router.get('/today', asyncHandler(async (req, res) => {
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  const tomorrow = new Date(today);
  tomorrow.setDate(tomorrow.getDate() + 1);

  const reminders = await Reminder.find({
    userId: req.user.id,
    isActive: true,
    nextRemindTime: {
      $gte: today,
      $lt: tomorrow
    }
  }).populate('medicineId', 'name imageUrl');

  res.json({
    success: true,
    data: reminders
  });
}));

// 创建用药提醒
router.post('/', asyncHandler(async (req, res) => {
  const { medicineId } = req.body;

  // 检查药品是否存在
  const medicine = await Medicine.findOne({
    _id: medicineId,
    userId: req.user.id
  });

  if (!medicine) {
    res.status(404);
    throw new Error('药品不存在');
  }

  const reminder = await Reminder.create({
    ...req.body,
    userId: req.user.id
  });

  res.status(201).json({
    success: true,
    data: reminder
  });
}));

// 更新用药提醒
router.put('/:id', asyncHandler(async (req, res) => {
  const reminder = await Reminder.findOneAndUpdate(
    { _id: req.params.id, userId: req.user.id },
    req.body,
    { new: true, runValidators: true }
  );

  if (!reminder) {
    res.status(404);
    throw new Error('提醒不存在');
  }

  res.json({
    success: true,
    data: reminder
  });
}));

// 删除用药提醒
router.delete('/:id', asyncHandler(async (req, res) => {
  const reminder = await Reminder.findOneAndDelete({
    _id: req.params.id,
    userId: req.user.id
  });

  if (!reminder) {
    res.status(404);
    throw new Error('提醒不存在');
  }

  res.json({
    success: true,
    data: {}
  });
}));

// 切换提醒状态
router.patch('/:id/toggle', asyncHandler(async (req, res) => {
  const reminder = await Reminder.findOne({
    _id: req.params.id,
    userId: req.user.id
  });

  if (!reminder) {
    res.status(404);
    throw new Error('提醒不存在');
  }

  reminder.isActive = !reminder.isActive;
  await reminder.save();

  res.json({
    success: true,
    data: reminder
  });
}));

module.exports = router;